package cn.lyf.myblog.dataFlow;

import java.lang.reflect.*;
import java.util.*;

public class DeepCopy {
    @SuppressWarnings("unchecked")
    public static <T> T copy(T b) {
        try {
            if (b instanceof String || b instanceof Character || b instanceof Number || b instanceof Boolean)
                return b;
            T a = (T) b.getClass().getConstructor().newInstance();
            for (Field f : getAllFields(b))
                f.set(a, copy(f.get(b)));
            return a;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    static List<Field> getAllFields(Object o) {
        List<Field> list = new ArrayList<>();
        Class<?> clazz = o.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                list.addAll(Arrays.asList(clazz.getDeclaredFields()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
